﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.Data;

namespace DivisonsCodeTools.Business
{
    public class DataBase
    {
        MySqlConnection Connection;
        MySqlCommand Command;
        MySqlDataAdapter Adapter;

        public DataBase(string connectstring)
        {
            Connection = new MySqlConnection(connectstring);
            Connection.Open();
        }

        public bool InsertBatch(List<DivisonInfo> list, string tableName)
        {
            Adapter = new MySqlDataAdapter("select * from " + tableName + " where 1=2", Connection);
            DataSet dataset = new DataSet();
            Adapter.Fill(dataset, tableName);
            DataTable datatable = dataset.Tables[0];
            for (int i = 0; i < list.Count; i++)
            {
                DataRow row = datatable.NewRow();
                row["Code"] = list[i].Code;
                row["Name"] = list[i].Name;
                row["Level"] = list[i].Level;
                row["ParentCode"] = list[i].ParentCode;
                datatable.Rows.Add(row);
            }
            Command = new MySqlCommand("Insert into " + tableName + "(Code,Name,Level,ParentCode) VALUES (@Code,@Name,@Level,@ParentCode)", Connection);
            Command.Parameters.Add("@Code", MySqlDbType.VarChar, 15, "Code");
            Command.Parameters.Add("@Name", MySqlDbType.VarChar, 60, "Name");
            Command.Parameters.Add("@Level", MySqlDbType.Int16, 11, "Level");
            Command.Parameters.Add("@ParentCode", MySqlDbType.VarChar, 15, "ParentCode");
            Adapter.InsertCommand = Command;
            Adapter.Update(dataset, tableName);
            return true;
        }

        public bool InsertBathForSQL(List<DivisonInfo> list, string tableName)
        {
            string sql = "";
            for (int i = 0; i < list.Count; i++)
            {
                string temsql = "Insert into " + tableName + "(Code,Name,Level,ParentCode) VALUES ('" + list[i].Code + "','" + list[i].Name + "'," + list[i].Level + ",'" + list[i].ParentCode + "');";
                sql += temsql;
            }
            Command = new MySqlCommand(sql, Connection);
            Command.ExecuteNonQuery();
            Command.Dispose();
            Connection.Close();
            Connection.Dispose();
            return true;
        }

    }
}
